package com.bite.rabbitmq.listener;

import com.bite.rabbitmq.constant.Constants;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class DLListener {
    // 正常消费
    // 注意：如果是手动确认 那么应该将acknowledge-mode 设置为 manual
    // 不然就会提示"unknown delivery tag 1"的错误
//    @RabbitListener(queues = Constants.NORMAL_QUEUE)
    public void listener1(Message message, Channel channel) throws Exception {
        long tag = message.getMessageProperties().getDeliveryTag();
        try {
            System.out.println("收到[" + Constants.NORMAL_QUEUE + "]的消息 message: "
                    + new String(message.getBody()) + ", tag: " + tag);
            int i = 0/0; // 抛出异常
            System.out.println("业务处理完成...");
            channel.basicAck(tag, false);
        } catch (Exception e) {
            // 被拒绝并且不重新入队 那么就回变为死信
            channel.basicNack(tag, false, false);
        }
    }

    // 死信消费
    // 死信 + ttl 可以实现延迟发布的效果
    @RabbitListener(queues = Constants.DL_QUEUE)
    public void listener2(Message message) throws Exception {
        long tag = message.getMessageProperties().getDeliveryTag();
        System.out.println("在" + new Date() + " 收到[" + Constants.DL_QUEUE + "]的消息 message: "
                + new String(message.getBody()) + ", tag: " + tag);
    }
}
